//
//  LTMessageFileBody.m
//  linktuIOS
//
//  Created by 俊松何 on 2017/6/16.
//  Copyright © 2017年 tianxie. All rights reserved.
//

#import "LTMessageFileBody.h"

static const NSString *filePath = @"chatfilebuffer";

@implementation LTMessageFileBody


-(instancetype)initWithData:(NSData *)data
{
    if(self = [super init])
    {
    
        [self saveData:data];

    
    }
    return self;
}
-(NSString *)localFilePath
{
    
    NSArray *arrDocumentPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *documentPath=[arrDocumentPaths objectAtIndex:0];
    _localFilePath = [NSString stringWithFormat:@"%@/%@",documentPath,_relativelocalFilePath];
    
    return _localFilePath;
    
}

-(void)saveData:(NSData *)data
{
    
    NSString *filename = [self getfileName:self.fileName];
    NSArray *arrDocumentPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *documentPath=[arrDocumentPaths objectAtIndex:0];
    
    documentPath = [NSString stringWithFormat:@"%@/%@",documentPath,filePath];
    
    
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if(![fileManager fileExistsAtPath:documentPath])
    {
        [fileManager createDirectoryAtPath:documentPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *failePath = [NSString stringWithFormat:@"%@/%@",documentPath,filename];
    _relativelocalFilePath = [NSString stringWithFormat:@"%@/%@",filePath,filename];
    
    [fileManager createFileAtPath:failePath contents:data attributes:nil];
    
    
    
}

//文件命名
-(NSString *)getfileName:(NSString *)name
{
    //随机数
    NSInteger rand = arc4random();
    long timesp = [[NSDate date] timeIntervalSince1970] * 1000;
    NSString *objectName = [NSString stringWithFormat:@"%d%ld%@",rand,timesp,name];
    return objectName;
}



@end
